<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="108px">
      <el-form-item label="优惠券名称" prop="name">
        <el-input
            v-model="queryParams.name"
            placeholder="请输入优惠券名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="折扣类型" prop="discountType">
        <el-select v-model="queryParams.discountType" placeholder="请选择折扣类型" clearable style="
        width: 180px;">
          <el-option
              v-for="dict in discount_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="推广方式" prop="obtainWay">
        <el-select v-model="queryParams.obtainWay" placeholder="请选择推广方式" clearable style="width: 180px;">
          <el-option
              v-for="dict in obtain_way"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 180px;">
          <el-option
              v-for="dict in coupon_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['market:coupon:add']"
        >新增
        </el-button>
      </el-col>

      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="couponList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="优惠券id" align="center" prop="id" v-if="false"/>
      <el-table-column label="优惠券名称" align="center" prop="name" width="160"/>
      <el-table-column label="优惠券类型" align="center" prop="type">
        <template #default="scope">
          <dict-tag :options="coupon_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="折扣类型" align="center" prop="discountType">
        <template #default="scope">
          <dict-tag :options="discount_type" :value="scope.row.discountType"/>
        </template>
      </el-table-column>
      <el-table-column label="折扣值" align="center" prop="discountValue" sortable/>
      <el-table-column label="使用门槛" align="center" prop="thresholdAmount" sortable/>
      <el-table-column label="推广方式" align="center" prop="obtainWay">
        <template #default="scope">
          <dict-tag :options="obtain_way" :value="scope.row.obtainWay"/>
        </template>
      </el-table-column>
      <el-table-column label="开始发放时间" align="center" prop="issueBeginTime" width="130" sortable>
        <template #default="scope">
          <span>{{ parseTime(scope.row.issueBeginTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束发放时间" align="center" prop="issueEndTime" width="130" sortable>
        <template #default="scope">
          <span>{{ parseTime(scope.row.issueEndTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="有效期" align="center" prop="termDays" sortable/>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="coupon_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="总数量" align="center" prop="totalNum" sortable/>
      <el-table-column label="已发行数量" align="center" prop="issueNum"/>
      <el-table-column label="已使用数量" align="center" prop="usedNum"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['market:coupon:edit']">修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['market:coupon:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改优惠券的规则信息对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="couponRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="优惠券名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入优惠券名称"/>
        </el-form-item>
        <el-form-item label="优惠券类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择优惠券类型">
            <el-option
                v-for="dict in coupon_type"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="折扣类型" prop="discountType">
          <el-select v-model="form.discountType" placeholder="请选择折扣类型">
            <el-option
                v-for="dict in discount_type"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="折扣值" prop="discountValue">
          <el-input v-model="form.discountValue" placeholder="请输入折扣值"/>
        </el-form-item>
        <el-form-item label="使用门槛" prop="thresholdAmount">
          <el-input v-model="form.thresholdAmount" placeholder="请输入使用门槛"/>
        </el-form-item>
        <el-form-item label="最高优惠金额" prop="maxDiscountAmount">
          <el-input v-model="form.maxDiscountAmount" placeholder="请输入最高优惠金额"/>
        </el-form-item>
        <el-form-item label="推广方式" prop="obtainWay">
          <el-select v-model="form.obtainWay" placeholder="请选择推广方式">
            <el-option
                v-for="dict in obtain_way"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始发放时间" prop="issueBeginTime">
          <el-date-picker clearable
                          v-model="form.issueBeginTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择开始发放时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束发放时间" prop="issueEndTime">
          <el-date-picker clearable
                          v-model="form.issueEndTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择结束发放时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="有效期天数" prop="termDays">
          <el-input v-model="form.termDays" placeholder="请输入有效期天数"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
                v-for="dict in coupon_status"
                :key="dict.value"
                :label="parseInt(dict.value)"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="总数量" prop="totalNum">
          <el-input v-model="form.totalNum" placeholder="请输入总数量"/>
        </el-form-item>
        <el-form-item label="限领数量" prop="userLimit">
          <el-input v-model="form.userLimit" placeholder="请输入限领数量"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Coupon">
import {listCoupon, getCoupon, delCoupon, addCoupon, updateCoupon} from "@/api/market/coupon";

const {proxy} = getCurrentInstance();
const {
  coupon_type,
  discount_type,
  obtain_way,
  coupon_status,
  specific
} = proxy.useDict('coupon_type', 'discount_type', 'obtain_way', 'coupon_status', 'specific');

const couponList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    discountType: null,
    obtainWay: null,
    status: null,
  },
  rules: {
    name: [
      {required: true, message: "优惠券名称不能为空", trigger: "blur"}
    ],
    type: [
      {required: true, message: "优惠券类型不能为空", trigger: "change"}
    ],
    discountType: [
      {required: true, message: "折扣类型不能为空", trigger: "change"}
    ],
    specific: [
      {required: true, message: "使用范围不能为空", trigger: "blur"}
    ],
    discountValue: [
      {required: true, message: "折扣值不能为空", trigger: "blur"}
    ],
    thresholdAmount: [
      {required: true, message: "使用门槛不能为空", trigger: "blur"}
    ],
    maxDiscountAmount: [
      {required: true, message: "最高优惠金额不能为空", trigger: "blur"}
    ],
    obtainWay: [
      {required: true, message: "推广方式不能为空", trigger: "change"}
    ],
    termDays: [
      {required: true, message: "有效期天数不能为空", trigger: "blur"}
    ],
    status: [
      {required: true, message: "状态不能为空", trigger: "change"}
    ],
  }
});

const {queryParams, form, rules} = toRefs(data);

/** 查询优惠券的规则信息列表 */
function getList() {
  loading.value = true;
  listCoupon(queryParams.value).then(response => {
    couponList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    type: null,
    discountType: null,
    specific: null,
    discountValue: null,
    thresholdAmount: null,
    maxDiscountAmount: null,
    obtainWay: null,
    issueBeginTime: null,
    issueEndTime: null,
    termDays: null,
    termBeginTime: null,
    termEndTime: null,
    status: null,
    totalNum: null,
    issueNum: null,
    usedNum: null,
    userLimit: null,
    extParam: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null
  };
  proxy.resetForm("couponRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加优惠券的规则信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getCoupon(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改优惠券的规则信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["couponRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateCoupon(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCoupon(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除优惠券的规则信息编号为"' + _ids + '"的数据项？').then(function () {
    return delCoupon(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('market/coupon/export', {
    ...queryParams.value
  }, `coupon_${new Date().getTime()}.xlsx`)
}

getList();
</script>
